package com.ews.onlineexchange.service;

import java.text.NumberFormat;
import java.util.Calendar;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;

@Stateless
public class BulletinSeqNoGenerator {
	
	private static final String PREFIX = "DYZJCS";
	
	@Inject
	EntityManager entityManager;
	
	static NumberFormat nf;
	static {
		nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(0);
		nf.setMinimumIntegerDigits(4);
		nf.setGroupingUsed(false);
	}
	
	public String getNextSeqNo() {
		Calendar cal = Calendar.getInstance();
		StringBuilder sb = new StringBuilder();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		int day = cal.get(Calendar.DAY_OF_MONTH);
		sb	.append(PREFIX)
			.append(year)
			.append(month)
			.append(day)
			.append(nf.format(getApplyCount(year, month, day) + 2));
		return sb.toString();
	}

	private static final String QUERY_APPLY_COUNT_EQL = ""
			+ "	SELECT		count(bulletin)"
			+ "	FROM		Bulletin bulletin"
			+ "	WHERE		bulletin.serialNumber LIKE CONCAT(:seqNo, '%')	";
	private Long getApplyCount(int year, int month, int day) {
		Query query = entityManager.createQuery(QUERY_APPLY_COUNT_EQL);
		query.setParameter("seqNo", PREFIX.concat(Integer.toString(year)).concat(Integer.toString(month)).concat(Integer.toString(day)));
		return (Long) query.getSingleResult();
	}
	
}
